//型号管理
const { Controller } = require('egg');
const { searchQuery, errorParams } = require('../utils/tools');
const { mysqlName } = require("../utils/config")
const { omit } = require('loadsh')
const { MACHINE_MODEL, AGENCY, MACHINE_WAREHOSING } = mysqlName
class HomeController extends Controller {
    async agencyList() {
        const { ctx } = this;
        const params = ctx.request.body || {};
        const tableName = AGENCY;
        const { sqlQuery } = searchQuery(tableName, params, 1, 50)
        const model = searchQuery(MACHINE_MODEL, params, 1, 50)
        try {
            const result = await ctx.app.mysql.query(sqlQuery);
            const modeData = await ctx.app.mysql.query(model.sqlQuery); //查询一下型号库，拿出型号名称字段 
            if (!result && !result.length) return;
            const data = result.map((item, index) => {
                const itemData = modeData.find(ite => item.angecy_type === ite.value);
                return {
                    ...item,
                    modelName: itemData.name
                }
            })
            ctx.body = {
                status: 200,
                msg: '',
                data: data,
            };
        } catch (error) {
            console.log(error, 'error')
            ctx.body = {
                status: 500,
                msg: '查询异常',
            };
        }

    }
    async machineList() {
        const { ctx } = this;
        const body = ctx.request.body || {};
        const params = body.data || {};
        const pageInfo = body.pageInfo
        const tableName = MACHINE_MODEL;
        const { sqlQuery, sqlCount } = searchQuery(tableName, params, 1, 100)
        const agencySql = searchQuery(AGENCY, { id: params.agency_id }, 1, 100, 'like')
        try {
            const data = await ctx.app.mysql.query(sqlQuery);
            const agencyData = await ctx.app.mysql.query(agencySql.sqlQuery, {}, 1, 100);
            const countObj = await ctx.app.mysql.query(sqlCount)

            let newData = data.map(item => {
                const agency_name = agencyData.find(ite => ite.id == item.agency_id)
                return {
                    ...item,
                    agency_name: agency_name.name,
                    agency_type: agency_name.value,
                    active_method: JSON.parse(item.active_method)
                }
            })
            newData = await Promise.all(newData.map(async (item) => {
                //查机具入库列表，查询出来闲置机器数量和 机器总数
                const total_count_sql = searchQuery(MACHINE_WAREHOSING, { agency_id: item.agency_id }, 1, 100) //机器总数sql
                const total_unbound_count_sql = searchQuery(MACHINE_WAREHOSING, { agency_id: item.agency_id, bind_status: 2 }, 1, 100) //闲置机器数
                const total_count = await ctx.app.mysql.query(total_count_sql.sqlCount)
                const total_unbound_count = await ctx.app.mysql.query(total_unbound_count_sql.sqlCount)
                return {
                    ...item,
                    total_count: total_count[0].total,
                    total_unbound_count: total_unbound_count[0].total
                }
            })).then(res => {
                return res;
            })
            ctx.body = {
                status: 200,
                data: newData,
                pageNum: 1,
                pageSize: 100,
                total: countObj[0].total,

            };

        } catch (error) {
            console.log(error, 'error')
            ctx.body = {
                status: 500,
                msg: '查询异常',
            };
        }

    }
    async createModel() {
        const { ctx } = this;
        const body = ctx.request.body || {};
        const requireParams = ['name', 'active_amount', 'active_method', 'agency_type']; //必传的参数
        const params = body;
        params.active_method = JSON.stringify(body.active_method)
        const tableName = MACHINE_MODEL;
        const { sqlQuery, sqlCount } = searchQuery(AGENCY, { value: params.angecy_type }, 1, 100)
        if (!errorParams(params, requireParams)) {
            ctx.body = {
                status: 400,
                msg: '缺少参数',
            };
            return;
        }
        try {
            const angecyData = await ctx.app.mysql.query(sqlQuery)
            const itemAngecy = angecyData.find(item => item.value === params.agency_type)
            console.log(itemAngecy, 'itemAngecy')
            const newParams = omit(params, 'agency_type');
            const data = await ctx.app.mysql.insert(tableName, { ...newParams, agency_id: itemAngecy.id });
            ctx.body = {
                status: 200,
                data: data.insertId
            };

        } catch (error) {
            console.log(error, 'error')
            ctx.body = {
                status: 500,
                msg: "数据库异常"
            };
            // ctx.body = {
            //     status: 500,
            //     msg: '查询异常',
            // };
        }

    }
    async updateModel() {
        const { ctx } = this;
        const body = ctx.request.body || {};
        const requireParams = ['id', 'name', 'active_amount', 'active_method']; //必传的参数
        const params = body;
        const tableName = MACHINE_MODEL;
        params.active_method = JSON.stringify(body.active_method)
        const newParams = omit(params, 'agency_type')
        if (!errorParams(params, requireParams)) {
            ctx.body = {
                status: 400,
                msg: '缺少参数',
            };
            return;
        }
        try {
            const data = await ctx.app.mysql.update(tableName, newParams);
            ctx.body = {
                status: 200,
                msg: "更新成功",
                data: params.id
            };
        } catch (error) {
            console.log(error, 'error')
            ctx.body = {
                status: 500,
                msg: ''
            };
        }
    }
    async deleteModel() {
        //删除型号
        const { ctx } = this;
        const body = ctx.request.body || {};
        const params = body;
        const tableName = MACHINE_MODEL;
        if (!params.id) {
            ctx.body = {
                status: 400,
                msg: "缺少id",
            };
            return;
        }
        try {
            const data = await ctx.app.mysql.delete(tableName, { id: params.id });
            ctx.body = {
                status: 200,
                msg: "删除成功",
                data: params.id
            };
        } catch (error) {
            ctx.body = {
                status: 500,
                msg: ''
            };
        }
    }
}

module.exports = HomeController;